TOOL.Category    = "Conna's Tools"
TOOL.Name        = "#Crate Tool"
TOOL.Command     = nil
TOOL.ConfigName  = ""

// ConVars

TOOL.ClientConVar["Scale"] = "1"

// Client

if (CLIENT) then
	// Tool
	
	language.Add("Tool_crate_name", "Crate Tool")
	language.Add("Tool_crate_desc", "Create a scaleable crate with collision")
	language.Add("Tool_crate_0", "Left click to spawn a Crate")
	
	// Other
	
	language.Add("Undone_crate", "Undone Crate")
end

// Message

function TOOL:Message(Text)
	if (SERVER) then
		self:GetOwner():SendLua("GAMEMODE:AddNotify('"..Text.."', NOTIFY_GENERIC, 10)")
		self:GetOwner():SendLua("surface.PlaySound('ambient/water/drip"..math.random(1, 4)..".wav')")
	end
end

// Left click

function TOOL:LeftClick(Trace)
	if(CLIENT) then
		return true
	end
	
	// Locals
	
	local Player = self:GetOwner()

	local Scale = self:GetClientNumber("Scale")
	
	// Keep it nice and whole
	
	Scale = math.Clamp(Scale, 1, 10)
	
	// Spawn angles
	
	local Ang = Trace.HitNormal:Angle()
	
	Ang.pitch = Ang.pitch + 90
	
	// Spawn it

	local Crate = CreateCrate(Player, Ang, Trace.HitPos, Scale)
	
	if not (Crate) then return false end
	
	// Position
	
	local Minimum = Crate:OBBMins()
	
	Crate:SetPos(Trace.HitPos - Trace.HitNormal * Minimum.z)
	
	// Undo
	
	undo.Create("crate")
		undo.AddEntity(Crate)
		undo.SetPlayer(Player)
	undo.Finish()
	
	// Add count
	
	Player:AddCount("props", Crate)
	
	Player:AddCleanup("props", Crate)
	
	return true, Crate
end

// Make it

if (SERVER) then
	function CreateCrate(Player, Ang, Pos, Scale, Nocollide, Vel, Avel, Frozen)
		if (!Player:CheckLimit("props")) then return false end
		
		// Crate
		
		local Crate = ents.Create("gmod_crate")
		
		Crate:SetModel("models/props/de_dust/du_crate_64x64.mdl")
		Crate:SetAngles(Ang)
		Crate:SetPos(Pos)
		Crate:SetEntityScale(Scale)
		Crate:Spawn()
		
		// Other
		
		Crate:SetPlayer(Player)
		
		// Frozen and nocollide
		
		if (Frozen) then Crate:GetPhysicsObject():EnableMotion(false) end
		
		if (Nocollide) then Crate:GetPhysicsObject():EnableCollisions(false) end
		
		// Return the entity
		
		return Crate
	end
	
	duplicator.RegisterEntityClass("gmod_crate", CreateCrate, "Ang", "Pos", "Scale", "Nocollide", "Vel", "Avel", "Frozen")
end

// Control panel

function TOOL.BuildCPanel(Panel)
	Panel:AddControl("Header", {Text = "#Tool_crate_name", Description = "#Tool_crate_desc"})
	
	Panel:AddControl("Slider", {Label = "Scale", Type = "Integer", Min = 1, Max = 10, Command = "crate_Scale"})
end